package com.cube.saintaugustin.activity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import com.cube.saintaugustin.R;
import com.cube.saintaugustin.common.CommonValues;
import com.cube.saintaugustin.common.MyApplication;
import com.cube.saintaugustin.common.RequestHttpThread;
import com.cube.saintaugustin.model.GoogleMapkiUtil;

public class SearchBranchListActivity extends FragmentActivity implements
        OnMapClickListener, OnClickListener, ConnectionCallbacks,
        OnConnectionFailedListener, LocationListener,
        OnMyLocationButtonClickListener {

    private GoogleMap mMap;
    private LocationClient mLocationClient;
    private LatLng mCurrentLatLng = null;
    private LatLng mSearchLatLng = null;
    private GoogleMapkiUtil mMapKiUtil = null;
    private ProgressDialog mProgressDialog;
    private ArrayList<String> arrData = null;
    private SendMassgeHandler mMainHandler = null;
    private requestThread mRqstThread = null;
    private Spinner mFirstSpinner = null;
    private Spinner mSecondSpinner = null;
    private boolean isFirst = true;

    private static final LocationRequest REQUEST = LocationRequest.create()
            .setInterval(5000) // 5 seconds
            .setFastestInterval(16) // 16ms = 60fps
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    private static final int SEND_THREAD_COMPLETE = 0;

    private static final int REQUEST_FIRST_SPINNER = 0;
    private static final int REQUEST_SECOND_SPINNER = 1;
    private int mSpinnerRequestType = REQUEST_FIRST_SPINNER;

    // Google Map 검색어
    // 이 검색어를 "생어거스틴" 같은 걸로 하면 주소 검색할 때
    // 그 지역에 "생어거스틴"이 없으면 맵에서 에러 발생 함.
    private static String MAP_SEARCH_KEYWORD = "초등학교";

    private String[] ZOOM_LEVEL_11 = { "서울", "인천", "대전", "세종", "대구", "괒우",
            "울산", "부산" };
    private static final String[] ZOOM_LEVEL_9 = { "경기", "강원", "충북", "충남",
            "경북", "경남", "전북", "전남", "제주" };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mng_3);

        this.overridePendingTransition(R.animator.start_enter_3,
                R.animator.start_exit);

        mMainHandler = new SendMassgeHandler();

        // 뒤로가기 버큰
        Button btnBack = (Button) findViewById(R.id.btn_back);
        btnBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ImageButton btnList = (ImageButton) findViewById(R.id.btn_map2list);
        btnList.setOnClickListener(this);

        Button srchBtn = (Button) findViewById(R.id.btn_srchAdr);
        srchBtn.setOnClickListener(this);

        mMapKiUtil = new GoogleMapkiUtil();

        setUpMapIfNeeded();
        initSpinner();

        mRqstThread = new requestThread();
        mRqstThread.start();
    }

    @Override
    public void finish() {
        super.finish();
        this.overridePendingTransition(R.animator.end_enter,
                R.animator.end_exit_3);
    }

    @Override
    protected void onResume() {
        if (mLocationClient == null) {
            mLocationClient = new LocationClient(getApplicationContext(), this,
                    this);
        }

        if (mLocationClient != null) {
            mLocationClient.connect();
        }

        super.onResume();
    }

    @Override
    protected void onPause() {
        if (mLocationClient != null) {
            mLocationClient.disconnect();
        }

        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_map2list:
                if (mSearchLatLng != null) {
                    Intent intent = new Intent(this,
                            SearchBranchResultListActivity.class);

                    if (mFirstSpinner.getSelectedItem().toString()
                            .equals(getString(R.string.first_spinner_default))) {
                        intent.setAction(CommonValues.ACTION_SEARCH_POSITION);
                        intent.putExtra("latitude",
                                Double.toString(mSearchLatLng.latitude));
                        intent.putExtra("longitude",
                                Double.toString(mSearchLatLng.longitude));
                        startActivity(intent);
                    } else {
                        StringBuilder builder = new StringBuilder();
                        builder.append(mFirstSpinner.getSelectedItem()
                                .toString());

                        if (mSecondSpinner
                                .getSelectedItem()
                                .toString()
                                .equals(getString(R.string.second_spinner_default)) == false) {
                            builder.append(" ");
                            builder.append(mSecondSpinner.getSelectedItem()
                                    .toString());
                        }

                        intent.setAction(CommonValues.ACTION_SEARCH_REGION);
                        intent.putExtra("region", builder.toString());
                        startActivity(intent);
                    }
                }
                break;
            case R.id.btn_srchAdr:
                searchArea();
                break;
            default:
                break;
        }
    }

    @Override
    public void onMapClick(LatLng point) {

    }

    @Override
    public boolean onMyLocationButtonClick() {
        return false;
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {

    }

    @Override
    public void onConnected(Bundle arg0) {
        mLocationClient.requestLocationUpdates(REQUEST, this); // LocationListener
    }

    @Override
    public void onDisconnected() {

    }

    @Override
    public void onLocationChanged(Location location) {
        mCurrentLatLng = new LatLng(location.getLatitude(),
                location.getLongitude());

        ((MyApplication) getApplication()).setcLatitude(Double
                .toString(mCurrentLatLng.latitude));
        ((MyApplication) getApplication()).setcLongitude(Double
                .toString(mCurrentLatLng.longitude));

        if (isFirst) {
            mSearchLatLng = new LatLng(location.getLatitude(),
                    location.getLongitude());

            moveToPosition(mCurrentLatLng);

            isFirst = false;
        }
    }

    private void startPrgsDlg() {
        if (mProgressDialog == null || !mProgressDialog.isShowing()) {
            mProgressDialog = ProgressDialog.show(
                    SearchBranchListActivity.this, "Searching", "잠시만 기다려 주세요");
        }
    }

    private void stopPrgsDlg() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void setUpMapIfNeeded() {
        if (mMap == null) {
            mMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();
        }

        if (mMap != null) {
            mMap.setMyLocationEnabled(true);
            mMap.setOnMyLocationButtonClickListener(this);
            mMap.setOnMapClickListener(this);
            mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick(Marker arg0) {
                    Toast.makeText(getBaseContext(),
                            "You clicked on InfoWindow ...", Toast.LENGTH_LONG)
                            .show();
                }
            });
        }
    }

    private void moveToPosition(LatLng latLng) {
        if (mMap != null) {
            mMap.clear();

            CameraPosition cp = new CameraPosition.Builder().target(latLng)
                    .zoom(getZoomLevel()).build();
            mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp));

            // Get branch list each by condition.
            if (mFirstSpinner.getSelectedItem().toString()
                    .equals(getString(R.string.first_spinner_default))) {
                requestBranchListFromPosition(latLng);
            } else {
                requestBranchListFromRegion();
            }

            // requestG4List(latLng);
        } else {
            Log.e("Error", "GoogleMap is null. [in]moveToLocation");
        }
    }

    private void adjustToPoints(String[] results) {
        if (mMap != null) {
            mMap.clear();

            int length = Integer.valueOf(results.length / 3);
            // LatLng[] mPoints = new LatLng[length];

            for (int i = 0; i < length; i++) {
                LatLng latlng = new LatLng(
                        Double.parseDouble(results[i * 3 + 1]),
                        Double.parseDouble(results[i * 3 + 2]));

                mMap.addMarker(new MarkerOptions()
                        .position(latlng)
                        .title(results[i * 3])
                        .icon(BitmapDescriptorFactory.defaultMarker(i * 360
                                / length)));
            }
        } else {
            Log.e("Error", "GoogleMap is null. [in]adjustToPoints");
        }
    }

    private String getAddres(LatLng latLng) {
        String rslt = "정보없음";

        Geocoder gcK = new Geocoder(getApplicationContext(), Locale.KOREA);

        try {
            List<Address> addresses = gcK.getFromLocation(latLng.latitude,
                    latLng.longitude, 1);
            StringBuilder sb = new StringBuilder();

            if (null != addresses && addresses.size() > 0) {
                Address address = addresses.get(0);
                sb.append(address.getCountryName()).append("/");
                sb.append(address.getPostalCode()).append("/");
                sb.append(address.getLocality()).append("/");
                sb.append(address.getThoroughfare()).append("/");
                sb.append(address.getFeatureName());

                rslt = sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return rslt;
    }

    private String getSido(LatLng latLng) {
        String rslt = "선택";

        Geocoder gcK = new Geocoder(getApplicationContext(), Locale.KOREA);

        try {
            List<Address> addresses = gcK.getFromLocation(latLng.latitude,
                    latLng.longitude, 1);
            StringBuilder sb = new StringBuilder();

            if (null != addresses && addresses.size() > 0) {
                Address address = addresses.get(0);
                sb.append(address.getAdminArea()).append("/");

                rslt = sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return rslt;
    }

    private String getGugun(LatLng latLng) {
        String rslt = "선택";

        Geocoder gcK = new Geocoder(getApplicationContext(), Locale.KOREA);

        try {
            List<Address> addresses = gcK.getFromLocation(latLng.latitude,
                    latLng.longitude, 1);
            StringBuilder sb = new StringBuilder();

            if (null != addresses && addresses.size() > 0) {
                Address address = addresses.get(0);
                sb.append(address.getLocality()).append("/");

                rslt = sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return rslt;
    }

    private void searchArea() {
        String sido = mFirstSpinner.getSelectedItem().toString();
        String gugun = mSecondSpinner.getSelectedItem().toString();

        if ((mFirstSpinner.getSelectedItem().toString())
                .equals(getString(R.string.first_spinner_default))) {
            Toast.makeText(getBaseContext(),
                    getString(R.string.spinner_popup_title), Toast.LENGTH_SHORT)
                    .show();
            return;
        } else {
            // Start mProgressDialog
            startPrgsDlg();

            if (gugun.equals(getString(R.string.second_spinner_default))) {
                mMapKiUtil.requestMapSearch(new ResultHandler(
                        SearchBranchListActivity.this), MAP_SEARCH_KEYWORD,
                        "대한민국" + "+" + sido);
            } else {
                mMapKiUtil.requestMapSearch(new ResultHandler(
                        SearchBranchListActivity.this), MAP_SEARCH_KEYWORD,
                        "대한민국" + "+" + sido + "+" + gugun);
            }
        }
    }

    static class ResultHandler extends Handler {
        private final WeakReference<SearchBranchListActivity> mActivity;

        ResultHandler(SearchBranchListActivity activity) {
            mActivity = new WeakReference<SearchBranchListActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            SearchBranchListActivity activity = mActivity.get();

            if (activity != null) {
                activity.handleMessage(msg);
            }
        }
    }

    private void handleMessage(Message msg) {
        String result = msg.getData().getString(GoogleMapkiUtil.RESULT);
        ArrayList<String> searchList = new ArrayList<String>();

        try {
            if (result.equals(GoogleMapkiUtil.SUCCESS_RESULT)) {
                searchList = msg.getData().getStringArrayList("searchList");
            } else if (result.equals(GoogleMapkiUtil.TIMEOUT_RESULT)) {
                Toast.makeText(this, "네트워크 연결이 안됩니다.", Toast.LENGTH_SHORT)
                        .show();
                return;
            } else if (result.equals(GoogleMapkiUtil.FAIL_MAP_RESULT)) {
                Toast.makeText(this, "검색이 안됩니다.", Toast.LENGTH_SHORT).show();
                return;
            } else {
                Toast.makeText(this, mMapKiUtil.stringData, Toast.LENGTH_SHORT)
                        .show();
                return;
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        // Stop progressDialog
        stopPrgsDlg();

        // Toast.makeText(this, searchList.get(0) + "," + searchList.get(1) +
        // "," + searchList.get(2), Toast.LENGTH_SHORT).show();

        mSearchLatLng = new LatLng(Double.parseDouble((searchList.get(1))
                .toString()),
                Double.parseDouble((searchList.get(2)).toString()));

        moveToPosition(mSearchLatLng);
    }

    private void requestG4List(LatLng latLng) {
        String requestFileNm = "g4_list_near_a.php";

        String parm = "";
        parm += "longitude=" + latLng.longitude;
        parm += "&";
        parm += "latitude=" + latLng.latitude;

        String result = null;

        try {
            ArrayList<String> searchList = new ArrayList<String>();

            result = new RequestHttpThread(SearchBranchListActivity.this)
                    .execute(requestFileNm, parm).get();

            String[] rows = result.split("<row>");

            for (int i = 0; i < rows.length - 1; i++) {
                // Log.i("HTTP_RESULT_COLUMNS",rows[i]);
                String[] columns = rows[i].split("<col>");

                String storeName = columns[1];
                String adress = columns[3];
                String tel = columns[4];
                String longitude = columns[5];
                String latitude = columns[6];

                // get address by LatLng
                // LatLng loc = new LatLng(Double.parseDouble(latitude),
                // Double.parseDouble(longitude));
                // String adress = getAddres(loc);

                searchList.add(storeName);
                searchList.add(adress);
                searchList.add(tel);
                searchList.add(latitude);
                searchList.add(longitude);
            }

            String[] searches = searchList
                    .toArray(new String[searchList.size()]);

            // adjustToPoints(searches);
            markingPositions(searches);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private void requestBranchListFromPosition(LatLng latLng) {
        String requestFileNm = "get_branch_list_position.php";

        String parm = "";
        parm += "longitude=" + latLng.longitude;
        parm += "&";
        parm += "latitude=" + latLng.latitude;

        String result = null;

        try {
            ArrayList<String> searchList = new ArrayList<String>();

            result = new RequestHttpThread(SearchBranchListActivity.this)
                    .execute(requestFileNm, parm).get();

            String[] rows = result.split("<row>");

            for (int i = 0; i < rows.length - 1; i++) {
                // Log.i("HTTP_RESULT_COLUMNS",rows[i]);
                String[] columns = rows[i].split("<col>");

                String storeName = columns[1];
                String adress = columns[3];
                String tel = columns[4];
                String longitude = columns[5];
                String latitude = columns[6];

                // get address by LatLng
                // LatLng loc = new LatLng(Double.parseDouble(latitude),
                // Double.parseDouble(longitude));
                // String adress = getAddres(loc);

                searchList.add(storeName);
                searchList.add(adress);
                searchList.add(tel);
                searchList.add(latitude);
                searchList.add(longitude);
            }

            String[] searches = searchList
                    .toArray(new String[searchList.size()]);

            // adjustToPoints(searches);
            markingPositions(searches);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private void requestBranchListFromRegion() {
        String requestFileNm = "get_branch_list_region.php";

        String parm = "";
        parm += "region=" + mFirstSpinner.getSelectedItem().toString();

        if (mSecondSpinner.getSelectedItem().toString()
                .equals(getString(R.string.second_spinner_default)) == false) {
            parm += " ";
            parm += mSecondSpinner.getSelectedItem().toString();
        }

        String result = null;

        try {
            ArrayList<String> searchList = new ArrayList<String>();

            result = new RequestHttpThread(SearchBranchListActivity.this)
                    .execute(requestFileNm, parm).get();

            String[] rows = result.split("<row>");

            for (int i = 0; i < rows.length - 1; i++) {
                // Log.i("HTTP_RESULT_COLUMNS",rows[i]);
                String[] columns = rows[i].split("<col>");

                String storeName = columns[1];
                String adress = columns[3];
                String tel = columns[4];
                String longitude = columns[5];
                String latitude = columns[6];

                // get address by LatLng
                // LatLng loc = new LatLng(Double.parseDouble(latitude),
                // Double.parseDouble(longitude));
                // String adress = getAddres(loc);

                searchList.add(storeName);
                searchList.add(adress);
                searchList.add(tel);
                searchList.add(latitude);
                searchList.add(longitude);
            }

            String[] searches = searchList
                    .toArray(new String[searchList.size()]);

            // adjustToPoints(searches);
            markingPositions(searches);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private void markingPositions(String[] results) {
        if (mMap != null) {
            int length = Integer.valueOf(results.length / 5);

            for (int i = 0; i < length; i++) {
                String storeName = results[i * 5];
                String adress = results[i * 5 + 1];
                String tel = results[i * 5 + 2];
                LatLng latlng = new LatLng(
                        Double.parseDouble(results[i * 5 + 3]),
                        Double.parseDouble(results[i * 5 + 4]));

                // Marking
                MarkerOptions marker = new MarkerOptions();
                marker.position(latlng);
                marker.title("[" + storeName + "] " + adress + " (" + tel + ")");

                mMap.addMarker(marker);
            }
        } else {
            Log.e("Error", "GoogleMap is null. [in]adjustToPoints");
        }
    }

    private void requestSido() {
        String requestFileNm = "get_adrs_1.php";

        String parm = "";

        String result = null;

        try {
            arrData = new ArrayList<String>();

            result = new RequestHttpThread(SearchBranchListActivity.this)
                    .execute(requestFileNm, parm).get();

            String[] rows = result.split("<row>");

            arrData.add(getString(R.string.first_spinner_default));

            for (int i = 0; i < rows.length - 1; i++) {
                // Log.i("HTTP_RESULT_COLUMNS",rows[i]);
                String[] columns = rows[i].split("<col>");

                String sido = columns[0];

                arrData.add(sido);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private void requestGugun() {
        String requestFileNm = "get_adrs_2.php";

        String parm = "";
        parm += "sido=" + mFirstSpinner.getSelectedItem().toString();

        String result = null;

        try {
            arrData = new ArrayList<String>();

            result = new RequestHttpThread(SearchBranchListActivity.this)
                    .execute(requestFileNm, parm).get();

            String[] rows = result.split("<row>");

            arrData.add(getString(R.string.second_spinner_default));

            for (int i = 0; i < rows.length - 1; i++) {
                // Log.i("HTTP_RESULT_COLUMNS",rows[i]);
                String[] columns = rows[i].split("<col>");

                String gugun = columns[0];

                arrData.add(gugun);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private void initSpinner() {
        mFirstSpinner = (Spinner) findViewById(R.id.map_srch_near1);
        mSecondSpinner = (Spinner) findViewById(R.id.map_srch_near2);

        String[] sido = { getString(R.string.first_spinner_default) };
        SpinnerAdapter sidoAdapter = new SpinnerAdapter(this,
                android.R.layout.simple_spinner_dropdown_item, sido);
        mFirstSpinner.setPrompt(getString(R.string.spinner_popup_title));
        mFirstSpinner.setAdapter(sidoAdapter);
        mFirstSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            // Spinner init 시점에서 "onItemSelected"가 호출되기 때문에 이를 회피하기 위한 코드
            int firsttimeThrough = 0;

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                firsttimeThrough = firsttimeThrough + 1;

                if (firsttimeThrough > 1) {
                    mSpinnerRequestType = REQUEST_SECOND_SPINNER;
                    mRqstThread = new requestThread();
                    mRqstThread.start();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        String[] gugun = { getString(R.string.second_spinner_default) };
        SpinnerAdapter gugunAdapter = new SpinnerAdapter(this,
                android.R.layout.simple_spinner_dropdown_item, gugun);
        mSecondSpinner.setPrompt(getString(R.string.spinner_popup_title));
        mSecondSpinner.setAdapter(gugunAdapter);
        mSecondSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void adaptListView() {
        if (arrData != null) {
            String[] tt = new String[arrData.size()];

            for (int i = 0; i < arrData.size(); i++) {
                tt[i] = arrData.get(i);
            }

            SpinnerAdapter adapter = new SpinnerAdapter(this,
                    android.R.layout.simple_spinner_dropdown_item, tt);

            if (mSpinnerRequestType == REQUEST_FIRST_SPINNER) {
                mFirstSpinner.setAdapter(adapter);
            } else if (mSpinnerRequestType == REQUEST_SECOND_SPINNER) {
                mSecondSpinner.setAdapter(adapter);
            }
        } else {
            if (mRqstThread != null) {
                mRqstThread.stopThread();
            }

            Toast.makeText(getBaseContext(), "데이터 요청 실패", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    private float getZoomLevel() {
        String firstItem = mFirstSpinner.getSelectedItem().toString();
        String default1 = getString(R.string.first_spinner_default);
        String secondItem = mSecondSpinner.getSelectedItem().toString();
        String default2 = getString(R.string.second_spinner_default);
        float zoomLevel = 13;

        if (firstItem.equals(default1) == false) {
            if (secondItem.equals(default2)) {
                for (int i = 0; i < ZOOM_LEVEL_11.length; i++) {
                    if (firstItem.equals(ZOOM_LEVEL_11[i])) {
                        zoomLevel = 11;
                    }
                }

                for (int i = 0; i < ZOOM_LEVEL_9.length; i++) {
                    if (firstItem.equals(ZOOM_LEVEL_9[i])) {
                        zoomLevel = 9;
                    }
                }
            }
        }

        return zoomLevel;
    }

    class SendMassgeHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case SEND_THREAD_COMPLETE:
                    //
                    adaptListView();

                    if (mRqstThread != null) {
                        mRqstThread.stopThread();
                    }
                    break;
            }
        }
    }

    class requestThread extends Thread implements Runnable {
        private boolean isRunning = false;

        public requestThread() {
            isRunning = true;
        }

        public void isThreadState(boolean isRunning) {
            this.isRunning = isRunning;
        }

        public void stopThread() {
            isRunning = !isRunning;
        }

        @Override
        public void run() {
            super.run();

            if (mSpinnerRequestType == REQUEST_FIRST_SPINNER) {
                requestSido();
            } else if (mSpinnerRequestType == REQUEST_SECOND_SPINNER) {
                requestGugun();
            }

            Message msg = mMainHandler.obtainMessage();
            msg.what = SEND_THREAD_COMPLETE;
            mMainHandler.sendMessage(msg);
        }
    }

    public class SpinnerAdapter extends ArrayAdapter<String> {
        Context context;
        String[] items = new String[] {};

        public SpinnerAdapter(final Context context,
                final int textViewResourceId, final String[] objects) {
            super(context, textViewResourceId, objects);

            this.items = objects;
            this.context = context;
        }

        @Override
        public View getDropDownView(int position, View convertView,
                ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(
                        android.R.layout.simple_spinner_dropdown_item, parent,
                        false);
            }

            TextView tv = (TextView) convertView
                    .findViewById(android.R.id.text1);
            tv.setText(items[position]);
            tv.setTextColor(Color.BLUE);
            tv.setTextSize(14);
            tv.setHeight(45);

            return convertView;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(
                        android.R.layout.simple_spinner_item, parent, false);
            }

            TextView tv = (TextView) convertView
                    .findViewById(android.R.id.text1);
            tv.setText(items[position]);
            tv.setTextSize(14);

            return convertView;
        }
    }
}